// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});

/* Start to build the dimension to article list data object */
function buildDimension2ArticleListForUI(articleList) {
  let refactorArticleList = [];
  let firstArticleListObj = {};
  let secondArticleListObj = {};
  let thirdArticleListObj = {};
  let articleListLength = articleList.length;
  let breakPoint = 6;

  firstArticleListObj['index'] = "first";
  firstArticleListObj['list'] = articleList.slice(0, breakPoint);
  secondArticleListObj['index'] = "second";
  secondArticleListObj['list'] = articleList.slice(breakPoint, articleListLength - breakPoint);
  thirdArticleListObj['index'] = "third";
  thirdArticleListObj['list'] = articleList.slice(articleListLength - breakPoint);
  refactorArticleList.push(firstArticleListObj);
  refactorArticleList.push(secondArticleListObj);
  refactorArticleList.push(thirdArticleListObj);

  return refactorArticleList;
}

// 云函数入口函数
exports.main = async (event, context) => {
  return cloud.callFunction({
    name : "AggregatedLookUpWithSortAndLimitQuery",
    data : {
      queryRequest : event.queryRequest
    }
  })
  .then(res => {
    let resultSet = buildDimension2ArticleListForUI(res.result);
    console.log(`[数据库] AggregatedLookUpForHomePageSwiper : ${event.queryRequest.originCollection} [查询记录] 成功: `, resultSet);

    return resultSet;
  });
}